package com.hand.wfive.loginAndVip.ui

import android.content.Context
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.loginAndVip.ApiConfig
import com.hand.wfive.loginAndVip.LoginConfig
import com.hand.wfive.loginAndVip.MD5Util
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.loginAndVip.model.ApiModel
import com.hand.wfive.util.click.NoFastClickUtils
import com.qmuiteam.qmui.widget.QMUITopBarLayout
import com.rxjava.rxlife.RxLife
import kotlinx.android.synthetic.main.login_activity_register.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import rxhttp.wrapper.param.RxHttp

class RegisterActivity  : LoginBaseActivity() {

    companion object {
        @JvmStatic
        fun show(context: Context?, isBuy: Boolean) {
            context?.startActivity<RegisterActivity>("isBuy" to isBuy)
        }
    }

    private var isBuy = false

    override fun isStatusTextBlack() = true

    override fun getTopBar(): QMUITopBarLayout = topBar

    override fun loginSuccess() {

    }

    override fun getContentViewId() = R.layout.login_activity_register

    override fun init() {
        topBar.setTitle("账号注册")
        initLogin()

        // 登录页面回调注册
        /*val turnLogin = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                finish()
            }
        }
        val loginBtn = topBar.addRightTextButton("密码登录", R.id.top_bar_right_text)
        loginBtn.setTextColor(Color.parseColor("#AEAEAE"))
        loginBtn.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            intent.putExtra("isBuy", isBuy)
            turnLogin.launch(intent)
        }

        val api = WXAPIFactory.createWXAPI(this, LoginConfig.WeChatAppId, false)
        api.registerApp(LoginConfig.WeChatAppId)*/

    }

    fun registerBtnClick(v: View) {
        if (NoFastClickUtils.isFastClick()) return
        when (v) {
            login_huawei -> /*华为账号登录*/ huaweiLogin()
            login_wechat -> /*微信一键登录*/ wechatLogin()
            passwordOp -> /* 密码显示或隐藏 */ {
                passwordOp.isSelected = !passwordOp.isSelected
                if (passwordOp.isSelected) {
                    passwordOp.setImageResource(R.mipmap.login_password_show)
                    et_password.transformationMethod = HideReturnsTransformationMethod.getInstance()
                } else {
                    passwordOp.setImageResource(R.mipmap.login_password_hide)
                    et_password.transformationMethod = PasswordTransformationMethod.getInstance()
                }
                et_password.setSelection(et_password.length())
            }
            password1Op -> /* 密码1显示或隐藏 */ {
                password1Op.isSelected = !password1Op.isSelected
                if (password1Op.isSelected) {
                    password1Op.setImageResource(R.mipmap.login_password_show)
                    et_password1.transformationMethod =
                            HideReturnsTransformationMethod.getInstance()
                } else {
                    password1Op.setImageResource(R.mipmap.login_password_hide)
                    et_password1.transformationMethod = PasswordTransformationMethod.getInstance()
                }
                et_password1.setSelection(et_password1.length())
            }
            register -> /* 注册 */ check()
            login_privacy_policy -> /*隐私政策*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowPolicy)
            }
            login_user_agreement -> /*用户协议*/ {
                PrivacyActivity.showRule(mContext, PrivacyActivity.ShowUserAgreement)
            }
            login_policy -> /* 勾选隐私政策和用户协议 */ {
                login_policy_agree.isSelected = !login_policy_agree.isSelected
                if (login_policy_agree.isSelected) {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_sel)
                } else {
                    login_policy_agree.setImageResource(R.mipmap.login_checkbox_nor)
                }
            }
        }
    }

    /**** 注册 start ****/
    private fun check() {
        val name = et_account.text.toString()
        if (name.isEmpty()) {
            showNormalTip(topBar, "请输入账号")
            return
        }
        if (name.length < 6) {
            showNormalTip(topBar, "账号的长度不能少于6个字符")
            return
        }
        val pass = et_password.text.toString()
        if (pass.isEmpty()) {
            showNormalTip(topBar, "请输入密码")
            return
        }
        if (pass.length < 6) {
            showNormalTip(topBar, "密码的长度不能少于6个字符")
            return
        }
        val pass1 = et_password1.text.toString()
        if (pass != pass1) {
            showNormalTip(topBar, "密码不一致")
            return
        }
        if (!login_policy_agree.isSelected) {
            showNormalTip(topBar, "请阅读并勾选用户协议")
            return
        }
        register(name, name, pass, UserManager.LoginType_normal)
    }

    private fun register(name: String, pass: String) {
        showLoading("请稍后...")
        val password = MD5Util.getPasswordMd5(pass)
        RxHttp.postForm(ApiConfig.register)
                .add("appid", LoginConfig.AppId).add("username", name)
                .add("pwd", password).add("loginType", UserManager.LoginType_normal)
                .add("packageName", App.getContext().packageName)
                .asClass(ApiModel::class.java)
                .to(RxLife.toMain(this))
                .subscribe({ apiModel ->
                    hideLoading()
                    if (apiModel.code == ApiConfig.SUCCESSCODE) {
                        toast("注册成功")
                        val user = apiModel.obj
                        user.password = password
                        UserManager.getInstance().saveUser(user)
                        if (isBuy && user.isVip == 0) {
                            VipCenterActivity.show(mContext)
                        }
                        finish()
                    } else if (apiModel.code == ApiConfig.USEREXISTCODE) {
                        showErrorTip(topBar, "账号已存在")
                    } else {
                        if (TextUtils.isEmpty(apiModel.msg)) {
                            showErrorTip(topBar, "网络异常，请重试！")
                        } else {
                            showErrorTip(topBar, apiModel.msg)
                        }
                    }
                }, {
                    hideLoading()
                    showErrorTip(topBar, "网络异常，请重试！")
                })
    }
    /**** 注册 end ****/
}